//
//  ADScrollView.m
//  BMADScrollViewDemo
//
//  Created by Suny on 15/3/27.
//  Copyright (c) 2015年 Sensoro. All rights reserved.
//

#import "ADScrollView.h"

#define rightDirection 1
#define zeroDirection 0
#define INTERVALE 8
#define kdescriptionTextHeight     36
#define PAGE_HEIGHT kdescriptionTextHeight


@interface ADImageView ()

@property(nonatomic ,strong)UILabel *descriptionLabel;
@end
@implementation ADImageView

- (UILabel *)descriptionLabel
{
    if (!_descriptionLabel)
    {
        _descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,
                                                                      self.bounds.size.height - kdescriptionTextHeight,
                                                                      self.bounds.size.width
                                                                      , kdescriptionTextHeight)];
		
		_descriptionLabel.font = [UIFont systemFontOfSize:12];
		_descriptionLabel.backgroundColor =[UIColor clearColor];
		_descriptionLabel.textColor=[UIColor blackColor];
		_descriptionLabel.alpha = 0.8;
    }
    
    return _descriptionLabel;
}

- (UIColor *)descriptionBackgroundColor
{
    if (!_descriptionBackgroundColor)
    {
        _descriptionBackgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.7];
		
    }
    
    return _descriptionBackgroundColor;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame andModel:(id<ADModelDelegate>)model
{
    self = [self initWithFrame:frame];
    if (self)
    {
        self.adModel = model;
        
        UITapGestureRecognizer *tabGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(adImageViewClick)];
        tabGesture.numberOfTapsRequired = 1;
        [self addGestureRecognizer:tabGesture];
    }
    
    return self;
}


- (void)layoutSubviews
{
    [super layoutSubviews];
    
    self.descriptionLabel.frame = CGRectMake(0,
                                             self.bounds.size.height - kdescriptionTextHeight,
                                             self.bounds.size.width,
                                             kdescriptionTextHeight);
    [self addSubview:self.descriptionLabel];
    
    self.descriptionLabel.text = [self.adModel adDescription];
    [self setImage:[UIImage imageNamed:[self.adModel adImageUrl]]];
    self.descriptionLabel.backgroundColor = self.descriptionBackgroundColor;
    
    self.descriptionLabel.hidden = ![self.descriptionLabel.text length];
    
    
}


-(void)adImageViewClick
{
    [self.delegate tapAdImageView:self];
}


@end


@interface ADScrollView()<UIScrollViewDelegate,ADImageViewDelegate>
{
    int switchDirection;//方向
    
    UIScrollView *imageSV;//滚动视图
    UIPageControl *pageControl;
}
@end
static  int pageNumber;//页码

@implementation ADScrollView

- (void)dealloc
{
	[self.timer invalidate];
	self.timer = nil;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        
    }
    return self;
}
//自定义实例化方法
- (instancetype)initWithFrame:(CGRect)frame andModelArray:(NSArray *)modelArray
{
    self = [self initWithFrame:frame];
    if (self)
    {
        self.modelArray = modelArray;
        pageNumber=0;//设置当前页为1

        [self addADScrollView:modelArray.count height:self.bounds.size.height];
        [self addImages];
        [self addPageControl:modelArray.count];
        
        //设置NSTimer
        _timer = [NSTimer scheduledTimerWithTimeInterval:INTERVALE 
												  target:self 
												selector:@selector(runTimePage) 
												userInfo:nil
												 repeats:YES];
        
    }
    return self;
    
}


- (void)addADScrollView:(NSInteger)count height:(CGFloat)heightValue
{
    //初始化scrollView
    imageSV = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.bounds.size.width, heightValue)];
    //设置sview属性
    
    imageSV.directionalLockEnabled = YES;//锁定滑动的方向
    imageSV.pagingEnabled = YES;//滑到subview的边界
    imageSV.bounces = NO;
    imageSV.delegate = self;
    imageSV.showsVerticalScrollIndicator = NO;//不显示垂直滚动条
    imageSV.showsHorizontalScrollIndicator = NO;//不显示水平滚动条
    
    CGSize newSize = CGSizeMake(self.bounds.size.width * (count + 2),  imageSV.bounds.size.height);//设置scrollview的大小
    [imageSV setContentSize:newSize];
    [self addSubview:imageSV];
    
}

- (void)addImages
{
    for (NSInteger i = 0; i <= self.modelArray.count +1; i++)
    {
        NSInteger j = 0;
        //创建内容对象
        
        if (i != self.modelArray.count +1 && i != 0)
        {
            j = i - 1;
        }
        
        if (i == 0)
        {
            j = self.modelArray.count - 1;
        }
        else if(i == self.modelArray.count +1)
        {
            j = 0;
        }
        
        ADImageView *adImageView = [[ADImageView alloc] initWithFrame:CGRectMake(i * self.bounds.size.width,
                                                                                 0,
                                                                                 self.bounds.size.width, self.bounds.size.height) andModel:[self.modelArray objectAtIndex:j]];
        adImageView.userInteractionEnabled = YES;
        adImageView.delegate = self;
        //设置视图标示
        adImageView.tag = i;
        //添加视图
        [imageSV addSubview:adImageView];
    }
    [imageSV setContentOffset:CGPointMake(0, 0)];
    [imageSV scrollRectToVisible:CGRectMake(self.bounds.size.width,0,self.bounds.size.width,self.frame.size.height) animated:NO]; // 默认从序号1位置放第1页 ，序号0位置位置放第4页
    
}
- (void)addPageControl:(NSInteger)count
{
    CGRect rect =  CGRectMake(0, self.frame.size.height - PAGE_HEIGHT, self.bounds.size.width, PAGE_HEIGHT);
    pageControl = [[UIPageControl alloc]initWithFrame:rect];
	pageControl.numberOfPages = count;
	pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
	pageControl.currentPageIndicatorTintColor = [UIColor grayColor];
	[pageControl sizeToFit];
	
    if (_pageCenter.y == 0.0)
    {
        _pageCenter.x = self.bounds.size.width - pageControl.bounds.size.width/2 - 20;
		_pageCenter.y =  self.frame.size.height - PAGE_HEIGHT/2;
    }
    pageControl.center = _pageCenter;


    [self addSubview:pageControl];
    
}
//NSTimer方法
//-(void)changeView:(NSTimer *)timer
//{
//    NSLog(@"changeView");
//
//    BOOL isAuto = timer != nil;
//    if (pageNumber == imageNameArr.count) {
//        [imageSV setContentOffset:CGPointMake(WIDTH*pageNumber, 0) animated:YES];
//        pageNumber = 0;
//        [imageSV setContentOffset:CGPointMake(WIDTH*pageNumber, 0) animated:YES];
//        pageControl.currentPage = pageNumber;
//        return ;
//    }
//    //修改页码
//    if (pageNumber == 0 && isAuto) {
//        switchDirection = rightDirection;
//    }else if(pageNumber >= imageNameArr.count-1 && isAuto){
//        switchDirection = zeroDirection;
//    }
//
//    if (switchDirection == rightDirection && isAuto) {
//        pageNumber ++;
//    }else if (switchDirection == zeroDirection && isAuto){
//        pageNumber = 0;
//    }
//
//    //page++;
//    //    //判断是否大于上线
//    //    if (page==imageNameArr.count) {
//    //        //重置页码
//    //        page=0;
//    //    }
//    //设置滚动到第几页
//    [imageSV setContentOffset:CGPointMake(WIDTH*pageNumber, 0) animated:YES];
//    pageControl.currentPage = pageNumber;
//
//
//}

- (void)setPageCenter:(CGPoint)pageCenter
{
    pageControl.center = pageCenter;
}
//// called on finger up if the user dragged. decelerate is true if it will continue moving afterwards
//- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
//{
//    NSLog(@"scrollViewDidEndDragging");
//
//}

// called when scroll view grinds to a halt
//- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
//{
//    NSLog(@"scrollViewDidEndDecelerating");
//    CGPoint offset = scrollView.contentOffset;
//    pageNumber = (offset.x  + WIDTH * 0.5)/ WIDTH; // 0 1 2
//    NSLog(@"%f  %d",offset.x,pageNumber);
//    [self changeView:nil];
//
//}
// scrollview 委托函数
- (void)scrollViewDidScroll:(UIScrollView *)sender
{
    CGFloat pagewidth = imageSV.frame.size.width;
    int page = floor((imageSV.contentOffset.x - pagewidth/([self.modelArray count]+2))/pagewidth)+1;
    page --;  // 默认从第二页开始
    pageControl.currentPage = page;
}
// scrollview 委托函数
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGFloat pagewidth = imageSV.frame.size.width;
    int currentPage = floor((imageSV.contentOffset.x - pagewidth/ ([self.modelArray count]+2)) / pagewidth) + 1;
    if (currentPage==0)
    {
        [imageSV scrollRectToVisible:CGRectMake(self.bounds.size.width * [self.modelArray count],0,self.bounds.size.width,self.bounds.size.height)
							animated:NO]; // 序号0 最后1页
    }
    else if (currentPage==([self.modelArray count]+1))
    {
        [imageSV scrollRectToVisible:CGRectMake(self.bounds.size.width,0,self.bounds.size.width,self.bounds.size.height)
							animated:NO]; // 最后+1,循环第1页
    }
}
// pagecontrol 选择器的方法
- (void)turnPage
{
    NSInteger page = pageControl.currentPage; // 获取当前的page
    [imageSV scrollRectToVisible:CGRectMake(self.bounds.size.width*(page+1),0,self.bounds.size.width,self.bounds.size.height)
						animated:NO]; // 触摸pagecontroller那个点点 往后翻一页 +1
}
// 定时器 绑定的方法
- (void)runTimePage
{
    NSInteger page = pageControl.currentPage; // 获取当前的page
    page++;
    page = page > self.modelArray.count-1 ? 0 : page ;
    pageControl.currentPage = page;
    [self turnPage];
}

#pragma ADImageViewDelegate
- (void)tapAdImageView:(ADImageView *)adScrollView;
{
    //调用委托实现方法
    [self.delegate adScrollView:self didSelectModel:adScrollView.adModel];
}

@end
